﻿@{
    ViewBag.Title = "MockPubSub";
    Layout = "~/Views/Shared/_Page.cshtml";
}

<h2>Mock Subscribe/Publish by JQuery Callback</h2>
<br />
<h3>Path: @ViewBag.Path</h3>
<br />
<p>
    The general idea behind pub/sub (Publish/Subscribe, or, the Observer pattern) 
    is the promotion of loose coupling in applications. 
    Rather than single objects calling on the methods of other objects, 
    an object instead subscribes to a specific task or activity of another object and is notified when it occurs. 
    Observers are also called Subscribers, and we refer to the object being observed as the Publisher (or the subject). 
    Publishers notify subscribers when events occur.
</p>
<h3>See the result on console</h3>
<br />

<script type="text/javascript" src="/JS/Demo/Callback/PubSub.js"></script>
<script type="text/javascript">
    function callback_func1(value) {
        ZEUS.DEBUG.log("Callback Function[1] Returns: " + value);
    }

    function callback_func2(value) {
        ZEUS.DEBUG.log("Callback Function[2] Returns: " + value);
    }

    $(document).ready(function () {
        // Subscribers
        ZEUS.DEBUG.log("topic1 subscribes func1 & func2");
        $.Topic("topic1").subscribe(callback_func1);
        $.Topic("topic1").subscribe(callback_func2);

        ZEUS.DEBUG.log("topic2 subscribes func1");
        $.Topic("topic2").subscribe(callback_func1);
        ZEUS.DEBUG.log("*************************************************************************");

        // Publisher
        ZEUS.DEBUG.log("topic1 publishes events:");
        $.Topic("topic1").publish("Hello David!");
        ZEUS.DEBUG.log("topic2 publishes events:");
        $.Topic("topic2").publish("Well Done!");
        ZEUS.DEBUG.log("*************************************************************************");
        ZEUS.DEBUG.log("<br />");

        // Subscribe to the mailArrived notification
        $.Topic("topic3").subscribe(callback_func1);

        // Create a new instance of Deferreds
        var dfd = $.Deferred();

        // Define a new topic (without directly publishing)
        var topic = $.Topic("topic3");

        // When the deferred has been resolved, publish a
        // notification to subscribers
        dfd.done(topic.publish);

        // Here the Deferred is being resolved with a message
        // that will be passed back to subscribers. It's possible to
        // easily integrate this into a more complex routine
        // (eg. waiting on an ajax call to complete) so that
        // messages are only published once the task has actually
        // finished.
        dfd.resolve("it's been published!");
    });
</script>

